package com.birdy.controller;

import com.birdy.code.CheckComment;
import com.birdy.dto.Response;
import com.birdy.jwt.service.IEncryptService;
import com.birdy.service.ICheckService;
import com.birdy.vo.Check;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;

/**
 * @author birdy
 * @date 2022/5/4 8:41 AM
 */
@Slf4j
@RestController
@RequestMapping("/check")
public class CheckController {
    @Autowired
    private ICheckService checkService;
    @Autowired
    private IEncryptService encryptService;

    @PostMapping("/add")
    public Response check(@RequestBody Check check) {
        try {
            // 获取openid
            String openid = encryptService.decryptBase64Password(check.getToken());
            check.setOpenid(openid);
            int score = checkService.addCheck(check);
            String comment = CheckComment.comment(score);
            return Response.builder().res(Response.SUCCESS).data("comment", comment).build();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Response.fail("occur some error");

    }
    @GetMapping("/get_latest")
    public Response getLatest(@RequestParam String token) {
        try {
            String openid = encryptService.decryptBase64Password(token);
            Timestamp latestDay = checkService.getLatestDay(openid);
            return Response.builder().res(Response.SUCCESS).data("latest", latestDay).build();
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage());
            return Response.fail("invalid token");
        }
    }

}
